package com.wyz.socket.core.base.packet;

import java.io.Closeable;
import java.io.IOException;

public abstract class Packet<Stream extends Closeable> implements Closeable {
    // bytes
    public static final byte TYPE_MEMORY_BYTES = 1;
    // string
    public static final byte TYPE_MEMORY_STRING = 2;
    // file
    public static final byte TYPE_STREAM_FILE = 3;
    // 长链接流
    public static final byte TYPE_STREAM_DIRECT = 4;

    protected static final int MAX_PACKET_SiZE = Integer.MAX_VALUE ;

    protected int length;

    protected Stream stream;

    private byte[] info  ;

    public abstract byte type() ;

    public int length() {
        return length;
    }

    public final Stream open() {
        if (stream == null) {
            stream = createStream();
        }
        return stream;
    }

    @Override
    public final void close() throws IOException {
        if (stream != null) {
            onCloseStream(stream);
            stream = null;
        }
    }

    protected void onCloseStream(Stream stream) {
        try {
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected abstract Stream createStream();

    public byte[] getInfo(){
        return info;
    }

    public void setInfo(byte[] info){
        this.info = info ;
    }
}
